from flask.blueprints import Blueprint
from flask import request,make_response
from flask import current_app as app
from flask.json import jsonify
import json,os,uuid,time
from utils.comm import get_data,xtree
from utils.myfile import myfile
from db import DB

#导入文件
from flask import Blueprint
from xlrd import open_workbook

#后天导出文件
from io import BytesIO
from xlrd import open_workbook
from urllib.parse import quote
import xlsxwriter
import datetime
import mimetypes

bp_users = Blueprint('bp_users',__name__)


@bp_users.route('/oran', methods=['POST', 'GET'])
def orande():
    if request.method == 'POSt':
        pass
    else:
        sql = "select * from zuzhi"
        db_one = DB()
        res = db_one.find_all(sql)
        red = xtree(res)
        return jsonify({'code': 200, 'list': red})


@bp_users.route('/create', methods=['POST'])
def create():
    data = get_data()
    print(data)
    sql1 = "insert into zuzhi(name, coding, type, num, pid) values('{}', '{}', {}, {}, {})".format(data['name'],data['coding'], int(data['type']), int(data['num']), int(data['pid']))
    db_one = DB()
    db_one.update(sql1)
    return jsonify({'code': 200})


# 导入excel
@bp_users.route('/upload', methods=['POST'])
def uploads():
    print(request.files)
    fileilename = request.files['file']
    print(request.files['file'])
    fileilename.save(os.path.join('./static/' + fileilename.filename))
    name = 'static/' + fileilename.filename
    bk = open_workbook(name, encoding_override='utf-8')
    sh = bk.sheets()[0]
    nrows = sh.nrows
    ncols = sh.ncols
    # 行
    for i in range(2, nrows):
        row_date = sh.row_values(i)
        for x in range(0, ncols):
            print(row_date[x])
    return 'ok'

# 导出exls
@bp_users.route('/download', methods=["GET", "POST"])
def download():
    # 实例化二进制数据
    out = BytesIO()
    # 创建一个Excel实例
    workbook = xlsxwriter.Workbook(out)
    # 添加一个sheet，add_worksheet()，默认"Sheet1"，可自定义命名，add_worksheet("资产列表")
    table = workbook.add_worksheet()
    # table.write(行, 列, 字段名)
    # 行、列从 0 开始计数
    # 字段命名根据每个人使用情况而定，插入数据部分也是
    table.write(0, 0, "资产编号")
    table.write(0, 1, "资产名称")

    workbook.close()
    filename = quote("资产列表_{}.xls".format(datetime.datetime.now().strftime("%Y%m%d%H%M%S")))
    file = make_response(out.getvalue())
    out.close()
    mime_type = mimetypes.guess_type('%s.xls' % filename)[0]
    file.headers['Content-Type'] = mime_type
    file.headers["Cache-Control"] = "no-cache"
    file.headers['Content-Disposition'] = "attachment; filename*=utf-8''{}".format(filename)
    return file

@bp_users.route('/users', methods=['POST', 'GET'])
def users():
    if request.method == 'POST':
        data = get_data()
        sql = "insert into users(nickname, password, name, gender, mobile, email, job) values('{}', '{}', '{}', {}, '{}', '{}', '{}')".format(
            data['username'], data['password'], data['name'], int(data['genter']), data['phone'], data['email'], data['jobnum']
        )
        db_one = DB()
        db_one.update(sql)
        return jsonify({'code': 200})
    else:
        sql = "select * from users"
        db_one=DB()
        res = db_one.findall(sql)
        return jsonify({'code': 200, 'list1': res})


@bp_users.route('/duanxin')
def duanxin():
    mobile = request.args.get('mobile')
    value = r.str_get(mobile)
    if value:
        return jsonify({'code': 10010, 'meg': '已发送，请勿重复发送'})
    code = random.randint(1000, 9999)
    print(code)
    flag = send_message(mobile, code, 1)
    if flag:
        r.str_set(mobile, code, 60)
    else:
        pass
    return jsonify({"code": 200, 'meg': code})


@bp_users.route('/login', methods=['POST'])
def login():
    data = get_data()
    value = r.str_get(data['mobile'])
    if not value:
        return jsonify({'code': 4001, 'mes': '验证码过期，请重新发送'})
    if int(value) == int(data['code']):
        sql = "select * from admin_user where name='%s'" % (data['mobile'])
        db_one = DB()
        res = db_one.find(sql)
        if res:
            r.str_del(data['mobile'])
            startime = time.time()
            data = {'data': {'username': data['mobile'], 'userid': res['id'], 'iat': startime, 'exp': 3600}}
            token = jwte.jwt_en(data)
            redata = {'data': {'iat': startime, 'exp': 7200}}
            retoken = jwte.jwt_en(redata)
            rsql = "select r.* from roles_resource as rr inner join resources as r on rr.resource_id=r.id where rr.role_id=%d" % (
                int(res['role_id']))
            resources = db_one.findall(rsql)
            return jsonify({'code': 200, 'user': res, 'token': token, 'retoken': retoken, 'resources': resources})
        else:
            return jsonify({'code': 4003, 'meg': '不存在'})

    else:
        return jsonify({'code': 4002, 'meg': '验证码输入错误'})

